import * as PIXI from 'pixi.js';
import { v4 as uuidv4 } from 'uuid';

export function getTextureFromCache(app, name, url) {
  const { loader } = app;
  const cacheResource = loader.resources[name];
  let texture = cacheResource?.texture;

  // 资源不存在或preload出现error，因为preload失败对象仍然存在，仅仅有error对象
  if (!texture || cacheResource?.error) {
    let newUrl = url;
    if (url.indexOf('data:image') === -1) {
      newUrl = `${url}?retry=1`; // newUrl是由于同一链接loader会拿失败的那个继续用
    }
    texture = PIXI.Texture.from(newUrl);
  }

  return texture;
}

export function makeObjectDraggable(obj) {
  obj.interactive = true; // 使之可以被监听到事件

  /** 用于存储触发时的坐标位置 */
  let coordStartData = null;
  /** 用来标识是否在拖拽中 */
  let dragging = false;

  let originObjPosition = null;

  /**
   * 事件按下触发
   *
   * @param {PIXI.InteractionEvent} e
   */
  const onDragStart = (e) => {
    coordStartData = {
      x: e.data.global.x,
      y: e.data.global.y,
    };
    dragging = true;

    originObjPosition = { x: obj.x, y: obj.y };
  };

  /**
   * 事件抬起触发
   *
   */
  const onDragEnd = () => {
    coordStartData = null;
    dragging = false;
  };

  /**
   * 事件移动触发
   *
   */
  const onDragMove = (e) => {
    if (dragging) {
      const newPosition = e.data.global;
      if (coordStartData) {
        const distanceX = newPosition.x - coordStartData.x;
        const distanceY = newPosition.y - coordStartData.y;
        obj.x = originObjPosition.x + distanceX;
        obj.y = originObjPosition.y + distanceY;
      }
    }
  };

  // 绑定事件
  obj.on('pointerdown', onDragStart);
  obj.on('pointerup', onDragEnd);
  obj.on('pointerupoutside', onDragEnd);
  obj.on('pointermove', onDragMove);

  return obj;
}

export function getRandomId() {
  return uuidv4();
}

export function saveImg(src) {
  var blob = new Blob([''], { type: 'application/octet-stream' });
  var url = URL.createObjectURL(blob);
  var a = document.createElement('a');
  a.href = src;
  a.download = src.replace(/(.*\/)*([^.]+.*)/gi, '$2').split('?')[0];
  var e = document.createEvent('MouseEvents');
  e.initMouseEvent(
    'click',
    true,
    false,
    window,
    0,
    0,
    0,
    0,
    0,
    false,
    false,
    false,
    false,
    0,
    null
  );
  a.dispatchEvent(e);
  URL.revokeObjectURL(url);
}
